package com.lkx.kafka.monitor.service;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lkx.kafka.monitor.dto.ThroughputMetrics;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class FileStorageService {

    @Value("${kafka.monitor.data.storage-path:./data}")
    private String storagePath;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostConstruct
    public void init() {
        // 确保存储目录存在
        File directory = new File(storagePath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
    }

    /**
     * 保存数据到文件
     */
    public void saveData(Map<String, List<ThroughputMetrics>> data) {
        try {
            File file = new File(storagePath, "monitor_data.json");
            objectMapper.writeValue(file, data);
            log.info("数据已保存到文件: {}", file.getAbsolutePath());
        } catch (Exception e) {
            log.error("保存数据到文件失败", e);
        }
    }

    /**
     * 从文件加载数据
     */
    public Map<String, List<ThroughputMetrics>> loadData() {
        try {
            File file = new File(storagePath, "monitor_data.json");
            if (!file.exists()) {
                log.info("数据文件不存在，返回空数据");
                return new HashMap<>();
            }

            // 更简洁的泛型类型构造方式
            JavaType keyType = objectMapper.getTypeFactory().constructType(String.class);
            JavaType valueType = objectMapper.getTypeFactory().constructCollectionType(List.class, ThroughputMetrics.class);
            JavaType mapType = objectMapper.getTypeFactory().constructMapType(HashMap.class, keyType, valueType);

            Map<String, List<ThroughputMetrics>> data = objectMapper.readValue(file, mapType);
            log.info("从文件加载数据成功，共加载 {} 个主题的数据", data.size());
            return data;
        } catch (Exception e) {
            log.error("从文件加载数据失败", e);
            return new HashMap<>();
        }
    }


}
